// Created by Joe on 2017/7/13.

app.controller(
    'DrivingSchoolController',
    [
        'KEY', 'config', '$scope', '$location', '$timeout', 'UserService', 'DrivingSchoolService',
        function (KEY, config, $scope, $location, $timeout, UserService, DrivingSchoolService) {
            init();

            function init() {
                // set area and rate
                $scope.curCity = [{}, {
                    // cityName: config.curCity.cityName,
                    showName: '全城',
                    // areaCode: config.curCity.cityCode
                    areaCode: ''
                }];
                config.curCity.region.forEach(function (r) {
                    $scope.curCity.push({
                        // cityName: r.regionName,
                        showName: r.regionName,
                        areaCode: r.regionCode
                    });
                });
                $scope.rate = [
                    {},
                    {rate: 0, display: '通过率不限'},
                    {rate: 90, display: '通过率90%以上'},
                    {rate: 80, display: '通过率80%以上'},
                    {rate: 70, display: '通过率70%以上'},
                    {rate: 60, display: '通过率60%以上'}
                ];

                // set move
                $scope.position = config.DrivingSchool;

                // set page
                // @la/ra: left/right arrow <0[blur], 1[focus]>
                $scope.page = ['home', 'detail', 'mask'];
                $scope.panel = {detail: -1, empty: false, load: false};
                $scope.limit = {list: 5, detailMonth: 6};
                $scope.control = {
                    page: 0,
                    list: 0, listIndex: -1,
                    da: '', la: 0, ra: 0,
                    area: 1, rate: 1, mask: false
                };

                // current position
                $scope.cp = $scope.position[$scope.page[$scope.control.page]];

                // set focus
                // @ci: current id
                $scope.focus = {ci: $scope.cp[0].id};

                // set data
                $scope.data = {
                    list: [],
                    curList: [],
                    history: {address: '', name: '', content: [], curContent: {month: ''}}
                };

                // add logic
                addLogic();

                // get info
                $scope.panel.load = true;
                DrivingSchoolService.getDrivingSchoolList($scope.curCity[1].areaCode, 0)
                    .then(function (info) {
                        $scope.data.list = info;

                        $scope.data.curList = $scope.data.list.slice(
                            $scope.control.list, $scope.control.list + $scope.limit.list
                        );

                        if ($scope.data.list.length > $scope.limit.list)
                            $scope.control.da = 'arrow-down--blur';

                        $scope.panel.load = false;
                        $scope.panel.empty = $scope.data.list.length === 0;
                    });

                // ele action
                $scope.move = function (evt, cb) {
                    evt.preventDefault();
                    switch (evt.keyCode) {
                        case KEY.UP:
                            if ($scope.control.mask) {
                                if (evt.target.id === 'ds-mk1') {
                                    if ($scope.control.area > 1) $scope.control.area--;
                                } else {
                                    if ($scope.control.rate > 1) $scope.control.rate--;
                                }
                            } else {
                                if ($scope.control.list === 0 && $scope.control.listIndex === 0) {
                                    $scope.control.listIndex = -1;
                                    $scope.focus.ci = 'ds-h1';
                                    // force focus
                                    document.getElementById('ds-h1').focus();
                                } else {
                                    moveShim('up', 'dynamic');
                                }
                            }
                            break;
                        case KEY.DOWN:
                            if ($scope.control.mask) {
                                if (evt.target.id === 'ds-mk1') {
                                    if ($scope.control.area < $scope.curCity.length - 1) $scope.control.area++;
                                } else {
                                    if ($scope.control.rate < $scope.rate.length - 1) $scope.control.rate++;
                                }
                            } else {
                                if (evt.target.id === 'ds-h1' && $scope.data.list.length > 0) {
                                    $scope.control.listIndex = 0;
                                } else {
                                    moveShim('down', 'dynamic');
                                }
                            }
                            break;
                        case KEY.LEFT:
                            moveShim('left');
                            break;
                        case KEY.RIGHT:
                            moveShim('right');
                            break;
                        case KEY.ENTER:
                            cb instanceof Function && cb();
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
                document.addEventListener('keyup', arrowAction);
            }

            function addLogic() {
                // open filter
                $scope.openFilter = function () {
                    if ($scope.panel.load) return;
                    $scope.control.mask = true;
                    $scope.panel.empty = false;
                    $scope.cp = $scope.position['mask'];
                    resetFocus();
                };

                // close filter
                $scope.closeFilter = function (direct) {
                    return function () {
                        if (direct) $scope.panel.empty = $scope.data.list.length === 0;
                        $scope.control.mask = false;
                        $scope.cp = $scope.position['home'];
                        resetFocus();
                    };
                };

                // school search
                $scope.schoolSearch = function () {
                    $scope.data.list = [];
                    $scope.data.curList = [];
                    $scope.panel.empty = false;
                    $scope.panel.load = true;
                    $scope.control.da = '';
                    DrivingSchoolService.getDrivingSchoolList($scope.curCity[$scope.control.area].areaCode,
                        $scope.rate[$scope.control.rate].rate)
                        .then(function (info) {
                            $scope.data.list = info;

                            $scope.data.curList = $scope.data.list.slice(
                                $scope.control.list, $scope.control.list + $scope.limit.list
                            );

                            if ($scope.data.list.length > $scope.limit.list)
                                $scope.control.da = 'arrow-down--blur';

                            $scope.panel.load = false;
                            $scope.panel.empty = $scope.data.list.length === 0;
                        });
                    $scope.closeFilter()();
                };

                // goto detail
                $scope.gotoDetail = function () {
                    pageSwitch(1);

                    var curSchool = $scope.data.curList[$scope.control.listIndex];
                    $scope.data.history = {};
                    // $scope.panel.empty = false;
                    $scope.panel.load = true;
                    DrivingSchoolService.getDrivingSchoolDetail(curSchool.schoolId, $scope.limit.detailMonth)
                        .then(function (info) {
                            $scope.panel.load = false;
                            var history = info['driverSchoolInfoList'];
                            if (!history || history.length === 0) {
                                $scope.panel.empty = true;
                                return;
                            }
                            $scope.data.history.address = info['address'];
                            $scope.data.history.name = info['drivingSchoolName'];
                            $scope.data.history.content = info['driverSchoolInfoList'].slice(1);
                            $scope.data.history.curContent = history[0];
                            var totalMark = parseFloat($scope.data.history.curContent.totalMark, 10);
                            $timeout(function () {
                                drawDoughnut([totalMark, 100 - totalMark], ['#46a7e7', 'rgba(255, 255, 255, .2)']);
                            })
                        });
                };

            }

            function resetFocus(pos) {
                pos = pos || 0;
                $scope.focus.ci = $scope.cp[pos]['id'];
            }

            // @data<Array>, @color<Array>
            function drawDoughnut(data, color) {
                var canvas = document.getElementById('ds-canvas');
                var ctx = canvas.getContext('2d');
                var center = [canvas.width / 2 + 30, canvas.height / 2];
                var segment = [];

                var total = 0;
                data.forEach(function (d) {
                    total += d;
                });
                data.forEach(function (d) {
                    segment.push(Math.PI * 2 * d / total);
                });

                ctx.lineWidth = 18;
                var start = -Math.PI * .5;
                for (var i = 0; i < segment.length; i++) {
                    ctx.strokeStyle = color[i];
                    ctx.beginPath();
                    ctx.arc(center[0], center[1], 95, start, start + segment[i]);
                    ctx.stroke();
                    start += segment[i];
                }
            }

            function pageSwitch(page) {
                page = page || 0;
                $scope.control.page = page;
            }

            function moveShim(dir, type) {
                type = type || 'static';
                if (type === 'static') {
                    var curFocus = $scope.cp.filter(function (item) {
                        return item.id === $scope.focus.ci;
                    })[0];
                    if (curFocus['move'][dir] !== -1) {
                        $scope.focus.ci = curFocus['move'][dir];
                    }
                } else {
                    switch (dir) {
                        case 'up':
                            if ($scope.control.da && $scope.control.da !== 'arrow-down--blur') $scope.control.da = 'arrow-down--blur';
                            if ($scope.control.listIndex > 0) {
                                $scope.control.listIndex--;
                            } else {
                                if ($scope.control.list > 0) {
                                    $scope.data.curList = $scope.data.list.slice(
                                        --$scope.control.list, $scope.control.list + $scope.limit.list
                                    );
                                }
                            }
                            break;
                        case 'down':
                            if ($scope.control.listIndex < Math.min($scope.limit.list - 1, $scope.data.list.length - 1)) {
                                $scope.control.listIndex++;
                            } else {
                                if ($scope.control.list + $scope.limit.list < $scope.data.list.length) {
                                    $scope.data.curList = $scope.data.list.slice(
                                        ++$scope.control.list, $scope.control.list + $scope.limit.list
                                    );
                                }
                            }
                            if ($scope.control.list + $scope.limit.list === $scope.data.list.length
                                && $scope.control.listIndex === $scope.limit.list - 1)
                                $scope.control.da = 'arrow-up--blur';
                            break;
                    }
                }
            }

            function globalAction() {
                var left = function () {
                    if ($scope.control.page === 0) return;

                    $scope.control.ra = 1;
                    $scope.panel.detail = 1;
                };
                var right = function () {
                    if ($scope.control.page === 0) return;

                    $scope.control.la = 1;
                    $scope.panel.detail = 0;
                };
                var back = function () {
                    event.preventDefault();

                    // detail page
                    if ($scope.control.page === 1) {
                        $scope.panel.detail = 1;
                        $scope.panel.empty = false;
                        pageSwitch(0);
                        return;
                    }

                    // mask page
                    if ($scope.control.mask) {
                        $scope.closeFilter(true)();
                        return;
                    }

                    // home page
                    if (document.activeElement.id !== 'ds-h1') {
                        $scope.focus.ci = 'ds-h1';
                        // force focus
                        document.getElementById('ds-h1').focus();
                        $scope.control.list = 0;
                        $scope.control.listIndex = -1;
                        $scope.data.curList = $scope.data.list.slice(
                            $scope.control.list, $scope.control.list + $scope.limit.list
                        );
                        if ($scope.control.da) $scope.control.da = 'arrow-down--blur';
                        return;
                    }

                    $scope.$apply(function () {
                        $location.path('/home').replace();
                    });
                };

                switch (event.keyCode) {
                    case KEY.LEFT:
                        left();
                        break;
                    case KEY.RIGHT:
                        right();
                        break;
                    case KEY.BACK:
                        back();
                        break;
                }

                $scope.$digest();
            }

            function arrowAction() {
                if ($scope.control.page !== 1) return;
                switch (event.keyCode) {
                    case KEY.LEFT:
                        $scope.control.ra = 0;
                        break;
                    case KEY.RIGHT:
                        $scope.control.la = 0;
                        break;
                }

                $scope.$digest();
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', globalAction);
                document.removeEventListener('keyup', arrowAction);
            });
        }
    ]
);